package com.lxw.station.download;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lxw.station.dto.GitHubDTO;
import lombok.SneakyThrows;
import utils.DownloadUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class Dbeaver {
    @SneakyThrows
    public static void main(String[] args) {
        String s = new String(Files.readAllBytes(Paths.get("src/main/resources/github/dbeaver/version.json")), StandardCharsets.UTF_8);
        List<GitHubDTO> gitHubDTOS = JSON.parseArray(s).toJavaList(GitHubDTO.class);
//        for (GitHubDTO gitHubDTO : gitHubDTOS) {
//            String tagName = gitHubDTO.getTagName();
//            System.out.println("tagName = " + tagName);
//            for (String url : gitHubDTO.getUrls()) {
//                System.out.println("url = " + url);
//            }
//        }
        GitHubDTO gitHubDTO = gitHubDTOS.get(0);
        String tagName = gitHubDTO.getTagName();
        String path = "E:\\dbeaver\\" + tagName + "\\";
        for (String url : gitHubDTO.getUrls()) {
            String fileName = url.substring(url.lastIndexOf("/") + 1);
            DownloadUtils.downloadZipFile(url, path + fileName);
        }

    }

    private static void extracted() throws IOException {
        String s = new String(Files.readAllBytes(Paths.get("src/main/resources/github/dbeaver/dbeaver.json")), StandardCharsets.UTF_8);
        JSONArray jsonArray = JSON.parseArray(s);
        List<GitHubDTO> list = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String tag_name = jsonObject.getString("tag_name");
            GitHubDTO gitHubDTO = new GitHubDTO();
            list.add(gitHubDTO);
            gitHubDTO.setTagName(tag_name);
            JSONArray assets = jsonObject.getJSONArray("assets");
            for (int j = 0; j < assets.size(); j++) {
                JSONObject asset = assets.getJSONObject(j);
                gitHubDTO.getUrls().add(asset.getString("browser_download_url"));
            }
        }
        Files.write(Paths.get("src/main/resources/github/dbeaver/version.json"), JSON.toJSONString(list).getBytes(StandardCharsets.UTF_8));
    }
}
